package com.hema.auction.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.reyun.sdk.TrackingIO;
import com.hema.auction.R;
import com.hema.auction.activity.H5Activity;
import com.hema.auction.activity.MainActivity;
import com.hema.auction.base.BaseFragment;
import com.hema.auction.bean.ProfileInfo;
import com.hema.auction.event.TabIndexEvent;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.UrlManager;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.Utils;
import com.hema.auction.utils.manager.ScreenManager;
import com.hema.auction.widget.MyClickable;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * 描述:
 * 作者:john
 */
public class RegisterFragment extends BaseFragment {
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.iv_account_del)
    ImageView ivAccountDel;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.iv_pwd_eye)
    ImageView ivPwdEye;
    @BindView(R.id.et_confirm_pwd)
    EditText etConfirmPwd;
    @BindView(R.id.iv_confirm_pwd_eye)
    ImageView ivConfirmPwdEye;
    @BindView(R.id.cb_agreement)
    CheckBox cbAgreement;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    Unbinder unbinder;

    @Override
    protected int getLayout() {
        return R.layout.fragment_register;
    }

    @Override
    protected void init() {
        super.init();
        tvAgreement.setText(getClickableSpan());
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());

        etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etAccount.getText().toString().trim().length() > 0) {
                    ivAccountDel.setVisibility(View.VISIBLE);
                } else {
                    ivAccountDel.setVisibility(View.GONE);
                }
                updateBtn();
            }
        });
        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                updateBtn();
            }
        });
        etConfirmPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                updateBtn();
            }
        });
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                updateBtn();
            }
        });
    }

    private void updateBtn() {
        if (etAccount.getText().toString().trim().length() > 0 &&
                etPwd.getText().toString().trim().length() > 0 &&
                etConfirmPwd.getText().toString().trim().length() > 0 &&
                etCode.getText().toString().trim().length() > 0) {
            tvRegister.setEnabled(true);
            tvRegister.setTextColor(getResources().getColor(R.color.white));
            tvRegister.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else {
            tvRegister.setEnabled(false);
            tvRegister.setTextColor(getResources().getColor(R.color.gray99));
            tvRegister.setBackgroundColor(getResources().getColor(R.color.layout_bg));
        }
    }


    @OnClick({R.id.iv_account_del, R.id.tv_send_code, R.id.tv_register, R.id.iv_pwd_eye, R.id.iv_confirm_pwd_eye})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_account_del:
                etAccount.setText("");
                break;
            case R.id.tv_send_code:
                getCode();
                break;
            case R.id.tv_register:
                if (cbAgreement.isChecked()) {
                    if (etPwd.getText().toString().equals(etConfirmPwd.getText().toString())) {
                        isAutoDismissDialog = false;
                        showProgressDialog();
                        HttpManager.getInstance(getActivity()).checkCode(etAccount.getText().toString(), etCode.getText().toString(), this);
                    } else {
                        showToastSafe(R.string.pwd_inconsistency);
                    }
                } else {
                    showToastSafe(R.string.please_agree_privacy_agreement);
                }

                break;
            case R.id.iv_pwd_eye:
                if (etPwd.getTransformationMethod() instanceof HideReturnsTransformationMethod) {
                    ivPwdEye.setImageResource(R.drawable.ic_eye_def);
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    ivPwdEye.setImageResource(R.drawable.ic_eye_sel);
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                etPwd.setSelection(etPwd.getText().toString().length());
                break;
            case R.id.iv_confirm_pwd_eye:
                if (etConfirmPwd.getTransformationMethod() instanceof HideReturnsTransformationMethod) {
                    ivConfirmPwdEye.setImageResource(R.drawable.ic_eye_def);
                    etConfirmPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    ivConfirmPwdEye.setImageResource(R.drawable.ic_eye_sel);
                    etConfirmPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                etConfirmPwd.setSelection(etConfirmPwd.getText().toString().length());
                break;
        }
    }

    /**
     * 获取验证码
     */
    private void getCode() {
        if (Utils.isEmpty(etAccount.getText().toString())) {
            showToastSafe(R.string.phone_isempty);
        } else if (!Utils.isValidPhone(etAccount.getText().toString())) {
            showToastSafe(R.string.phone_error);
        } else {
            isAutoDismissDialog = true;
            showProgressDialog();
            HttpManager.getInstance(getActivity()).getCode(etAccount.getText().toString(), this);
        }
    }

    private CharSequence getClickableSpan() {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.EXTRA_TITLE, getString(R.string.reg_agreement));
                bundle.putString(Constant.EXTRA_URL, UrlManager.H5_REGISTER_AGREEMENT);
                intentTo(H5Activity.class, bundle);
            }
        };
        SpannableString spanableInfo = new SpannableString(tvAgreement.getText().toString());
        int start = 4;
        int end = 10;
        spanableInfo.setSpan(new MyClickable(getActivity(), listener), start, end, Spanned.SPAN_MARK_MARK);
        return spanableInfo;
    }


    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_SEND_CODE:
                try {
                    if (result.getInt("errcode") == 0) {
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_CHECK_CODE:
                try {
                    if (result.getInt("errcode") == 0) {
                        HttpManager.getInstance(getActivity()).register(etAccount.getText().toString().trim(), Utils.stringToMD5(etPwd.getText().toString().trim()), this);
                    } else {
                        showToastSafe(result);
                        dismissProgressDialog();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_REGISTER:
                try {
                    if (result.getInt("errcode") == 0) {
                        spManager.setIsLogin(true);
                        profileInfo = new Gson().fromJson(result.getJSONObject("data").toString(), ProfileInfo.class);
                        TrackingIO.setRegisterWithAccountID(profileInfo.getId());
                        setAlisa();
                        updateProfile();
                        spManager.setUserId(profileInfo.getId());
                        ScreenManager.getInstance().popAllActivitys(MainActivity.class);
                        EventBus.getDefault().post(new TabIndexEvent(3, profileInfo.isNewUser()));
                        getActivity().finish();
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onFailure(HttpTag httpTag, Call call, IOException e) {
        super.onFailure(httpTag, call, e);
        if (httpTag == HttpTag.TAG_CHECK_CODE) {
            dismissProgressDialog();
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        if (httpTag == HttpTag.TAG_REGISTER) {
            dismissProgressDialog();
        }
    }
}
